package com.MRSyc.controller;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.MRSyc.base.BaseController;
import com.MRSyc.config.MrConfig;
import com.MRSyc.config.PageModel;
import com.MRSyc.entity.FError;
import com.MRSyc.entity.ICStockBill;
import com.MRSyc.entity.ICStockBillEntry;
import com.MRSyc.entity.InboundDocument;
import com.MRSyc.entity.Pagination;
import com.MRSyc.entity.ReagentInboundDocument;
import com.MRSyc.entity.ReagentInboundDocumentVo;
import com.MRSyc.entity.TItem;
import com.MRSyc.entity.TUdiCode;
import com.MRSyc.mapper.ICStockBillEntryMapper;
import com.MRSyc.mapper.ICStockBillMapper;
import com.MRSyc.mapper.TItemMapper;
import com.MRSyc.mapper.TUdiCodeMapper;
import com.MRSyc.utils.ClientUtils;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import lombok.extern.slf4j.Slf4j;

/**
 *
 *
 *
 * @author Administrator
 */
@Slf4j
@Controller
@RequestMapping(value = "/")
public class PurchaseController extends BaseController {
	private ClientUtils client = new ClientUtils();
	/*
	 * @Autowired private ITUserinfoService userService;
	 * 
	 * @Autowired private ITUserRoleService userRoleService;
	 * 
	 * @Autowired private ITResourcesService resourcesService;
	 * 
	 * @Autowired private ITRoleResourcesService roleResourcesService;
	 * 
	 * @Autowired private ITUserExtService userExtServiceImpl;
	 */
	@Autowired
	ICStockBillMapper icMapper;
	
	@Autowired
	ICStockBillEntryMapper icEntryMapper;

	@Autowired
	private MrConfig mrconfig;
	
	@Autowired
	TItemMapper itemMapper;
	
	@Autowired
	TUdiCodeMapper codeMapper;

	private static final long PAGE_SIZE = 10L;
	
	private SimpleDateFormat format1=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	private SimpleDateFormat format3=new SimpleDateFormat("yyyy-MM");

	@RequestMapping(value = "/purchase/list", method = RequestMethod.GET)
	public String purchase_list() {

		return "purchase/purchase_list";
	}

	@RequestMapping(value = "/purchase/list", method = { RequestMethod.POST })
	@ResponseBody
	public PageModel list(String startDate, String endDate, String documentNumber, String salesOrderNumber,
			String documentType, PageModel<ReagentInboundDocumentVo> page) throws Exception {
		page.init();
		System.out.println("getClient_id = " + mrconfig.getClient_id());
		if(StringUtils.isNotEmpty(startDate)) {
			Map<String, String> params = new HashMap<>();
			if (StringUtils.isNotEmpty(startDate))
				params.put("startDate", startDate);
			if (StringUtils.isNotEmpty(endDate))
				params.put("endDate", endDate);
			if (StringUtils.isNotEmpty(documentNumber))
				params.put("documentNumber", documentNumber);
			if (StringUtils.isNotEmpty(salesOrderNumber))
				params.put("salesOrderNumber", salesOrderNumber);
			if (StringUtils.isNotEmpty(documentType))
				params.put("documentType", documentType);

			params.put("currentPage", "0");
			params.put("pageSize", "100");
			// params.put("documentType", "Inbound");
			Map<String, Object> map = getInboundList(params);
			List<ReagentInboundDocument> reagentInboundDocumentList = new ArrayList<>();
			List<ReagentInboundDocumentVo> reagentInboundDocumentVoList = new ArrayList<>();
			Pagination pagination = new Pagination();
			Object code = map.get("code");
			if (code != null) {
				switch (code.toString()) {
				case "200":
					Object result = map.get("result");
					System.out.println("result1 :"+result.toString());
					reagentInboundDocumentList = parseReagentInboundDocumentList(result);
					reagentInboundDocumentVoList=changeData(reagentInboundDocumentList,reagentInboundDocumentVoList);
					pagination = parsePagination(result);
					break;
				case "401":
					//未授权或授权到期重新授权
					Map<String, String> param = new HashMap<>();
					param.put("client_id", mrconfig.getClient_id());
					param.put("client_secret", mrconfig.getClient_secret());
					param.put("grant_type", mrconfig.getGrant_type());
					param.put("username", mrconfig.getUsername());
					param.put("password", mrconfig.getPassword());
					client.getToken(mrconfig.getLoginUrl(), param);
					//if(token!=null) param.put("Authorization", "Bearer "+token);
					map = getInboundList(params);
					code = map.get("code");
					if (code != null) {
						switch (code.toString()) {
						case "200":
							result = map.get("result");
							
							reagentInboundDocumentList = parseReagentInboundDocumentList(result);
							reagentInboundDocumentVoList=changeData(reagentInboundDocumentList,reagentInboundDocumentVoList);
							System.out.println("result2 :"+result.toString());
							pagination = parsePagination(result);
							break;
						}
					}
					break;
				case "403":
					break;
				case "404":
					break;
				}
			}
			page.packData(0, reagentInboundDocumentVoList);
		}else {
			page.packData(0, new ArrayList<>());
		}
		
		return page;
	}
	
	public List<ReagentInboundDocumentVo>  changeData(List<ReagentInboundDocument> reagentInboundDocumentList,List<ReagentInboundDocumentVo> reagentInboundDocumentVoList) {
		for(ReagentInboundDocument d:reagentInboundDocumentList) {
			List<InboundDocument> arrs=d.getInboundDocumentList();
			for(InboundDocument in:arrs) {
				ReagentInboundDocumentVo v=new ReagentInboundDocumentVo();
				v.setB2bUnit(d.getB2bUnit());
				v.setCreationTime(d.getCreationTime());
				v.setDocumentNo(d.getDocumentNo());
				v.setDocumentType(d.getDocumentType());
				v.setDocumentTypeDesc(d.getDocumentTypeDesc());
				v.setExternalOrderNo(d.getExternalOrderNo());
				v.setBatchNumber(in.getBatchNumber());
				v.setDueDate(in.getDueDate());
				v.setEntryNumber(in.getEntryNumber());
				v.setMaterialNumber(in.getMaterialNumber());
				v.setMaterialDesc(in.getMaterialDesc());
				v.setProductionDate(in.getProductionDate());
				v.setQuantity(in.getQuantity());
				v.setSalesUnitCode(in.getSalesUnitCode());
				v.setSalesUnitDesc(in.getSalesUnitDesc());
				v.setInboundDocumentList(d.getInboundDocumentList());
				reagentInboundDocumentVoList.add(v);
			}
		}
		return reagentInboundDocumentVoList;
	}

	/*
	 * 解析迈瑞接口返回的入库列表信息
	 */
	public List<ReagentInboundDocument> parseReagentInboundDocumentList(Object result) {
		List<ReagentInboundDocument> list = new ArrayList<>();
		JSONObject obj = JSONObject.parseObject(result.toString());
		if (obj != null) {
			JSONArray documents = obj.getJSONArray("documents");
			if (documents != null && documents.size() > 0) {
				for (int i = 0; i < documents.size(); i++) {
					JSONObject head = documents.getJSONObject(i);
					list.add(parseReagentInboundDocument(head));
				}
			}
		}
		return list;
	}

	public ReagentInboundDocument parseReagentInboundDocument(JSONObject head) {
		ReagentInboundDocument document = new ReagentInboundDocument();
		if (head != null) {
			String b2bUnit = head.getString("b2bUnit");
			String b2bUnitName = head.getString("b2bUnitName");
			String clientID = head.getString("clientID");
			String clientName = head.getString("clientName");
			String contactPerson = head.getString("contactPerson");
			String creationTime = head.getString("creationTime");
			String documentNo = head.getString("documentNo");
			String documentType = head.getString("documentType");
			String documentTypeDesc = head.getString("documentTypeDesc");
			String externalOrderNo = head.getString("externalOrderNo");
			String lender = head.getString("lender");
			String phoneNOOfSalesPerson = head.getString("phoneNOOfSalesPerson");
			String phoneNumber = head.getString("phoneNumber");
			String returnReason = head.getString("returnReason");
			String salesPerson = head.getString("salesPerson");
			String status = head.getString("status");

			JSONArray bodys = head.getJSONArray("reagentInboundDocumentEntries");
			List<InboundDocument> list = new ArrayList<>();
			if (bodys != null && bodys.size() > 0) {
				for (int j = 0; j < bodys.size(); j++) {
					JSONObject body = bodys.getJSONObject(j);
					list.add(parseInboundDocument(body));
				}
			}
			document.setB2bUnit(b2bUnit);
			document.setB2bUnitName(b2bUnitName);
			document.setClientID(clientID);
			document.setClientName(clientName);
			document.setContactPerson(contactPerson);
			document.setCreationTime(creationTime);
			document.setDocumentNo(documentNo);
			document.setDocumentType(documentType);
			document.setDocumentTypeDesc(documentTypeDesc);
			document.setExternalOrderNo(externalOrderNo);
			document.setInboundDocumentList(list);
			document.setLender(lender);
			document.setPhoneNOOfSalesPerson(phoneNOOfSalesPerson);
			document.setPhoneNumber(phoneNumber);
			document.setReturnReason(returnReason);
			document.setSalesPerson(salesPerson);
			document.setStatus(status);

		}
		return document;
	}

	public InboundDocument parseInboundDocument(JSONObject body) {
		InboundDocument document = new InboundDocument();
		if (body != null) {
			String batchNumber = body.getString("batchNumber");
			String dueDate = body.getString("dueDate");
			String entryNumber = body.getString("entryNumber");
			String materialDesc = body.getString("materialDesc");
			String materialNumber = body.getString("materialNumber");
			String orderEntryNumber = body.getString("orderEntryNumber");
			String productionDate = body.getString("productionDate");
			String quantity = body.getString("quantity");
			String salesUnitCode = body.getString("salesUnitCode");
			String salesUnitDesc = body.getString("salesUnitDesc");
			String documentNo = body.getString("documentNo");
			String price=body.getString("price");
			JSONArray udiCodeList = body.getJSONArray("udiCodeList");
			List<TUdiCode> udiCodes = new ArrayList<>();
			if (udiCodeList != null && udiCodeList.size() > 0) {
				for (int m = 0; m < udiCodeList.size(); m++) {
					JSONObject udiCode = udiCodeList.getJSONObject(m);
					udiCodes.add(parseUdiCode(udiCode));
				}
			}
			document.setBatchNumber(batchNumber);
			document.setDocumentNo(documentNo);
			document.setDueDate(dueDate);
			document.setEntryNumber(entryNumber);
			document.setMaterialDesc(materialDesc);
			document.setMaterialNumber(materialNumber);
			document.setOrderEntryNumber(orderEntryNumber);
			document.setProductionDate(productionDate);
			document.setQuantity(quantity);
			document.setSalesUnitCode(salesUnitCode);
			document.setSalesUnitDesc(salesUnitDesc);
			document.setUdiCodeList(udiCodes);
			document.setPrice(price);
		}
		return document;
	}

	public TUdiCode parseUdiCode(JSONObject udiCode) {
		TUdiCode u = new TUdiCode();

		if (udiCode != null) {
			String dueDate = udiCode.getString("dueDate");
			String materialNumber = udiCode.getString("materialNumber");
			String productUniName = udiCode.getString("productUniName");
			String productionDate = udiCode.getString("productionDate");
			String trackingCode = udiCode.getString("trackingCode");
			//String unit = udiCode.getString("unit");
			u.setFduedate(dueDate);
			u.setFmaterialNumber(materialNumber);
			u.setFproductionDate(productionDate);
			u.setFproductUniName(productUniName);
			u.setFtrackingCode(trackingCode);
		}
		return u;
	}

	public Pagination parsePagination(Object result) {
		Pagination pagination = new Pagination();
		JSONObject json = JSONObject.parseObject(result.toString());
		if (json != null) {
			JSONObject page = json.getJSONObject("pagination");
			if (page != null) {
				int currentPage = page.getInteger("page");
				int pageSize = page.getInteger("count");
				String sort = page.getString("sort");
				int totalPages = page.getInteger("totalPages");
				int totalResults = page.getInteger("totalCount");
				pagination.setCurrentPage(currentPage);
				pagination.setPageSize(pageSize);
				pagination.setSort(sort);
				pagination.setTotalPages(totalPages);
				pagination.setTotalResults(totalResults);
			}
		}

		return pagination;
	}

	public Map<String, Object> getInboundList(Map<String, String> params) {
		return client.getInboundList(mrconfig.getInboundUrl(), params);
	}

	@RequestMapping(value = "/purchase/implData", method = { RequestMethod.POST })
	@ResponseBody
	public Map<String,Object>  impData(@RequestBody ReagentInboundDocumentVo[] recordList) {
		//List<ReagentInboundDocument> reagentInboundDocumentList = JSON.parseArray(recordList, ReagentInboundDocument.class);
		System.out.println("impDta...."+recordList.length);
		Map<String,Object> map=new HashMap<>();
		try {
			int finterid=0;
			List<FError> errors=new ArrayList<>();
			for(ReagentInboundDocumentVo v:recordList) {
				List<ICStockBill> ics=checkICSTockBillIsExsits(v.getExternalOrderNo());
				if(ics!=null&&ics.size()>0) {
					ICStockBill icstock=ics.get(0);
					finterid=icstock.getFInterID();
				}else {
					finterid=icMapper.findMaxFInterID();
					insertICStockBill(finterid,v);
				}
				List<FError> arr=insertICStockBillEntry(v,finterid);
				for(FError err: arr) {
					errors.add(err);
				}
			}
			map.put("code", 200);
			map.put("error", errors);
			
		}catch(Exception e) {
			e.printStackTrace();
			map.put("code", 500);
		}

		return map;
		
	}
	
	/*
	 * 判断表头是否存在
	 */
	public List<ICStockBill> checkICSTockBillIsExsits(String externalOrderNo){
		QueryWrapper<ICStockBill> queryWrapper=new QueryWrapper<>();
		ICStockBill entity=new ICStockBill();
		entity.setFExplanation(externalOrderNo);
		queryWrapper.setEntity(entity);
		return icMapper.selectList(queryWrapper);
	}
	/*
	 * 判断表体是否存在
	 */
	public List<ICStockBillEntry> checkICSTockBillEntryIsExsits(String materialNumber,int finterId){
		QueryWrapper<ICStockBillEntry> queryWrapper=new QueryWrapper<>();
		ICStockBillEntry entity=new ICStockBillEntry();
		List<TItem> items=checkItemIsExsits(materialNumber);
		if(items!=null&&items.size()>0) {
			entity.setFItemID(items.get(0).getFItemID());
			entity.setFInterID(finterId);
			queryWrapper.setEntity(entity);
			return icEntryMapper.selectList(queryWrapper);
		}else {
			return new ArrayList<ICStockBillEntry>();
		}
	}
	
	/*
	 * 判断物料是否存在
	 */
	public List<TItem> checkItemIsExsits(String materialNumber){
		QueryWrapper<TItem> queryWrapper=new QueryWrapper<>();
		TItem entity=new TItem();
		entity.setFShortNumber(materialNumber);
		entity.setFItemClassID(4);
		queryWrapper.setEntity(entity);
		return itemMapper.selectList(queryWrapper);
	}
	
	/*
	 * 判断物料是否存在
	 */
	public List<TItem> checkItemIsExsits(String fnumber,String fname){
		QueryWrapper<TItem> queryWrapper=new QueryWrapper<>();
		TItem entity=new TItem();
		entity.setFNumber(fnumber);
		entity.setFName(fname);
		entity.setFItemClassID(7);
		queryWrapper.setEntity(entity);
		return itemMapper.selectList(queryWrapper);
	}
	/*
	 * 插入表头信息
	 */
	public int insertICStockBill(int finterid,ReagentInboundDocumentVo v) {
		ICStockBill ic=new ICStockBill();
		try {
			ic.setFBrNo("0");
			ic.setFInterID(finterid);
			ic.setFTranType(1);
			ic.setFDate(format1.parse(v.getCreationTime()));
			ic.setFBillNo(v.getDocumentNo());
			ic.setFDeptID(1042);
			ic.setFEmpID(0);
			ic.setFSupplyID(928);
			ic.setFManagerID(0);
			ic.setFSManagerID(306);
			ic.setFBillerID(16404);
			ic.setFrob(1);
			ic.setFStatus(0);
			ic.setFPOStyle(252);
			ic.setFMarketingStyle(12530);
			ic.setFSettleDate(format1.parse(v.getCreationTime()));
			ic.setFPOMode(36680);
			ic.setFYearPeriod(format3.format(format3.parse(v.getCreationTime())));
			ic.setFsourceType(37521);
			ic.setFISUpLoad(1059);
			ic.setFExplanation(v.getExternalOrderNo());   
		}catch(Exception e) {
			e.printStackTrace();
		}
		return icMapper.insert(ic);
	}
	/*
	 * 插入表体信息
	 */
	public List<FError> insertICStockBillEntry(ReagentInboundDocumentVo v,int finterid) {
		List<FError> errors=new ArrayList<>();
		List<InboundDocument> documents=v.getInboundDocumentList();
		int num=0;
		SimpleDateFormat f=new SimpleDateFormat("yyyy-MM-dd");
		for(int i=0;i<documents.size();i++) {
			
			List<TItem> items=checkItemIsExsits(documents.get(i).getMaterialNumber());
			if(items!=null&&items.size()>0) {
				List<ICStockBillEntry> entrys=checkICSTockBillEntryIsExsits(documents.get(i).getMaterialNumber(),finterid);
				if(entrys!=null&&entrys.size()>0) {
					
				}else {
					if(isExistICStockBillEntry(finterid, num+1)) num=icEntryMapper.selectMaxEntryID(finterid)+1;
					ICStockBillEntry entry=new ICStockBillEntry();
					entry.setFInterID(finterid);
					entry.setFBrNo("0");
					entry.setFEntryID(num+1);
					entry.setFItemID(items.get(0).getFItemID());
					if (documents.get(i).getQuantity()!=null) {
						entry.setFQty(Double.parseDouble(documents.get(i).getQuantity()));
						entry.setFAuxQty(Double.parseDouble(documents.get(i).getQuantity()));
					}
					if (documents.get(i).getPrice()!=null) entry.setFPurchasePrice(Double.parseDouble(documents.get(i).getPrice()));
					entry.setFBatchNo(documents.get(i).getBatchNumber());
					entry.setFManuBatchNo(documents.get(i).getBatchNumber());
					List<TItem> units=checkItemIsExsits(documents.get(i).getSalesUnitCode(),documents.get(i).getSalesUnitDesc());
					if(units!=null&&units.size()>0) {
						entry.setFUnitID(units.get(0).getFItemID());
					}else {
						FError error=new FError();
						error.setFname(documents.get(i).getSalesUnitDesc());
						error.setFcode(documents.get(i).getSalesUnitCode());
						error.setDesc("单位不匹配");
						errors.add(error);
						continue;
					}
					entry.setFDCStockID(943);
					entry.setFGMPPercent(100.0000000000);
					entry.setFGSPCheckState(506);
					entry.setFPlanMode(14036);
					entry.setFChkPassItem(1058);
					entry.setFSourceBillNo(v.getExternalOrderNo());
					if(StringUtils.isNotEmpty(documents.get(i).getProductionDate()))
						try {
							entry.setFKFDate(f.parse( documents.get(i).getProductionDate()));
						} catch (ParseException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					if(StringUtils.isNotEmpty(documents.get(i).getDueDate()))
						try {
							entry.setFPeriodDate(f.parse( documents.get(i).getDueDate()));
						} catch (ParseException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					if(icEntryMapper.insert(entry)>0) {
						insertUdiCode(documents.get(i).getUdiCodeList(),finterid);
					}
				}
				
			}else {
				FError error=new FError();
				error.setFname(documents.get(i).getMaterialDesc());
				error.setFcode(documents.get(i).getMaterialNumber());
				error.setDesc("短编码不存在或不匹配");
				errors.add(error);
			}
		}
		return errors;
	}
	
	/*
	 * 防止之前入库一批 又来一批 entryID重复无法插入的问题
	 */
	public boolean isExistICStockBillEntry(int finterId,int fentryId){
		QueryWrapper<ICStockBillEntry> queryWrapper=new QueryWrapper<>();
		ICStockBillEntry entity=new ICStockBillEntry();

		entity.setFInterID(finterId);
		entity.setFEntryID(fentryId);
		queryWrapper.setEntity(entity);
		List<ICStockBillEntry> list=icEntryMapper.selectList(queryWrapper);
		boolean flg=false;
		if(list!=null&&list.size()>0) flg=true;
		return flg;
	}
	
	/*
	 * 防止之前入库一批 又来一批 entryID重复无法插入的问题
	 */
	public boolean isExistTUdiCode(int finterId,TUdiCode u){
		QueryWrapper<TUdiCode> queryWrapper=new QueryWrapper<>();
		TUdiCode entity=new TUdiCode();

		entity.setFinterid(finterId);
		entity.setFmaterialNumber(u.getFmaterialNumber());
		entity.setFtrackingCode(u.getFtrackingCode());
		queryWrapper.setEntity(entity);
		List<TUdiCode> list=codeMapper.selectList(queryWrapper);
		boolean flg=false;
		if(list!=null&&list.size()>0) flg=true;
		return flg;
	}
	
	/*
	 * 插入追溯码信息
	 */
	public void insertUdiCode(List<TUdiCode> codes,int finterid) {
		for(TUdiCode u:codes) {
			if(!isExistTUdiCode(finterid,u)) {
				u.setFinterid(finterid);
				codeMapper.insert(u);
			}
		}
		
	}
	
	

}
